package com.my.algorithmlearning.leetcode;

/**
 * @ClassName Medium_152_MaxProduct
 * @Description 参考题解：https://leetcode.cn/problems/maximum-product-subarray/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--36/
 * @Author wanghaiwei
 * @Date 2023/5/18 17:24
 */
public class Medium_152_MaxProduct {

    public int maxProduct(int[] nums) {
        int max = Integer.MIN_VALUE;
        int imax = 1;
        int imin = 1;
        for (int num : nums) {
            if (num < 0) {
                //如果num小于0，则imax和imin交换
                int tmp = imax;
                imax = imin;
                imin = tmp;
            }
            imax = Math.max(imax * num, num);
            imin = Math.min(imin * num, num);
            max = Math.max(max, imax);
        }
        return max;
    }
}
